<template>
  <div class="order-detail-container">
    <!-- 面包屑导航 -->
    <div class="breadcrumb">
      <el-breadcrumb separator="/">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item :to="{ path: '/orders' }">我的订单</el-breadcrumb-item>
        <el-breadcrumb-item>订单详情</el-breadcrumb-item>
      </el-breadcrumb>
    </div>

    <!-- 加载状态 -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="6" animated />
    </div>

    <!-- 错误状态 -->
    <div v-else-if="error" class="error-container">
      <el-result icon="error" :title="error" sub-title="加载订单详情失败">
        <template #extra>
          <el-button type="primary" @click="loadOrderDetail">重新加载</el-button>
          <el-button @click="$router.back()">返回</el-button>
        </template>
      </el-result>
    </div>

    <!-- 订单详情内容 -->
    <div v-else class="order-detail-content">
      <!-- 订单状态卡片 -->
      <el-card class="status-card">
        <div class="status-header">
          <div class="status-info">
            <h2>订单详情</h2>
            <el-tag :type="getStatusTagType(orderDetail?.status)" size="large">
              {{ getStatusText(orderDetail?.status) }}
            </el-tag>
          </div>
          <div class="order-actions">
            <el-button 
              v-if="orderDetail?.status === 'PENDING'" 
              type="primary" 
              @click="goToPayment"
            >
              立即支付
            </el-button>
            <el-button 
              v-if="orderDetail?.status === 'PENDING'" 
              @click="cancelOrder"
            >
              取消订单
            </el-button>
            <el-button @click="$router.back()">返回</el-button>
          </div>
        </div>
        
        <div class="order-basic-info">
          <div class="info-item">
            <span class="label">订单编号：</span>
            <span class="value">{{ orderDetail?.orderNo }}</span>
            <el-button type="text" @click="copyOrderNo">复制</el-button>
          </div>
          <div class="info-item">
            <span class="label">创建时间：</span>
            <span class="value">{{ formatDate(orderDetail?.createdAt) }}</span>
          </div>
          <div class="info-item" v-if="orderDetail?.payTime">
            <span class="label">支付时间：</span>
            <span class="value">{{ formatDate(orderDetail?.payTime) }}</span>
          </div>
          <div class="info-item">
            <span class="label">支付方式：</span>
            <span class="value">{{ getPaymentMethodText(orderDetail?.paymentMethod) }}</span>
          </div>
        </div>
      </el-card>

      <!-- 订单信息卡片 -->
      <el-card class="order-info-card">
        <template #header>
          <div class="card-header">
            <span>订单信息</span>
          </div>
        </template>
        
        <div class="order-items">
          <div class="item-info">
            <div class="item-title">{{ orderDetail?.itemTitle }}</div>
            <div class="item-meta">
              <span class="item-type">{{ getItemTypeText(orderDetail?.type) }}</span>
            </div>
          </div>
        </div>
        
        <div class="order-amount">
          <div class="amount-row">
            <span class="label">商品金额：</span>
            <span class="value">¥{{ formatAmount(orderDetail?.originalAmount) }}</span>
          </div>
          <div class="amount-row" v-if="orderDetail?.discountAmount && orderDetail.discountAmount > 0">
            <span class="label">优惠金额：</span>
            <span class="value discount">-¥{{ formatAmount(orderDetail?.discountAmount) }}</span>
          </div>
          <div class="amount-row total">
            <span class="label">实付金额：</span>
            <span class="value total-amount">¥{{ formatAmount(orderDetail?.amount) }}</span>
          </div>
        </div>
      </el-card>

      <!-- 支付状态卡片 -->
      <el-card class="payment-status-card">
        <template #header>
          <div class="card-header">
            <span>支付状态</span>
          </div>
        </template>
        
        <div class="payment-info">
          <div class="payment-status">
            <el-tag :type="getPaymentStatusTagType(orderDetail?.paymentStatus)" size="large">
              {{ getPaymentStatusText(orderDetail?.paymentStatus) }}
            </el-tag>
          </div>
          
          <div v-if="orderDetail?.transactionId" class="transaction-info">
            <span class="label">交易号：</span>
            <span class="value">{{ orderDetail.transactionId }}</span>
          </div>
        </div>
      </el-card>
    </div>
  </div>
</template>

<script lang="ts">
import { defineComponent, ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { getOrder, cancelOrder as cancelOrderApi } from '@/api/order/order'
import type { OrdersQueryVO } from '@/types/Orders'

export default defineComponent({
  name: 'OrderDetailView',
  setup() {
    const route = useRoute()
    const router = useRouter()
    
    // 响应式数据
    const loading = ref(false)
    const error = ref('')
    const orderDetail = ref<OrdersQueryVO | null>(null)
    
    // 获取订单号
    const orderNo = route.query.orderNo as string
    
    // 加载订单详情
    const loadOrderDetail = async () => {
      if (!orderNo) {
        error.value = '缺少订单号参数'
        return
      }
      
      loading.value = true
      error.value = ''
      
      try {
        const response = await getOrder(orderNo)
        
        if (response.success) {
          orderDetail.value = response.data
        } else {
          throw new Error(response.message || '获取订单详情失败')
        }
      } catch (err) {
        error.value = err instanceof Error ? err.message : '加载订单详情失败'
      } finally {
        loading.value = false
      }
    }
    
    // 复制订单号
    const copyOrderNo = async () => {
      if (!orderDetail.value?.orderNo) return
      
      try {
        await navigator.clipboard.writeText(orderDetail.value.orderNo)
        ElMessage.success('订单号已复制')
      } catch (err) {
        ElMessage.error('复制失败')
      }
    }
    
    // 去支付
    const goToPayment = () => {
      if (!orderDetail.value) return
      
      // 跳转到支付页面
      router.push({
        path: '/order/payment',
        query: {
          itemType: orderDetail.value.type,
          itemId: orderDetail.value.itemId?.toString()
        }
      })
    }
    
    // 取消订单
    const cancelOrder = async () => {
      if (!orderDetail.value) return
      
      try {
        await ElMessageBox.confirm('确定要取消这个订单吗？', '确认取消', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        
        const response = await cancelOrderApi(orderDetail.value.id!)
        
        if (response.success) {
          ElMessage.success('订单已取消')
          // 重新加载订单详情
          loadOrderDetail()
        } else {
          throw new Error(response.message || '取消订单失败')
        }
      } catch (err) {
        if (err !== 'cancel') {
          ElMessage.error(err instanceof Error ? err.message : '取消订单失败')
        }
      }
    }
    
    // 格式化日期
    const formatDate = (dateString: string | null | undefined) => {
      if (!dateString) return ''
      const date = new Date(dateString)
      return date.toLocaleString('zh-CN')
    }
    
    // 格式化金额
    const formatAmount = (amount: number | null | undefined) => {
      return amount ? amount.toFixed(2) : '0.00'
    }
    
    // 获取订单状态标签类型
    const getStatusTagType = (status: string | null | undefined) => {
      if (!status) return 'default'
      const statusMap: Record<string, string> = {
        PENDING: 'warning',
        PROCESSING: 'primary',
        COMPLETED: 'success',
        CANCELLED: 'danger'
      }
      return statusMap[status] || 'default'
    }
    
    // 获取订单状态文本
    const getStatusText = (status: string | null | undefined) => {
      if (!status) return '未知'
      const statusMap: Record<string, string> = {
        PENDING: '待处理',
        PROCESSING: '处理中',
        COMPLETED: '已完成',
        CANCELLED: '已取消'
      }
      return statusMap[status] || '未知状态'
    }
    
    // 获取支付状态标签类型
    const getPaymentStatusTagType = (status: string | null | undefined) => {
      if (!status) return 'default'
      const statusMap: Record<string, string> = {
        PENDING: 'warning',
        PAID: 'success',
        FAILED: 'danger',
        REFUNDED: 'info'
      }
      return statusMap[status] || 'default'
    }
    
    // 获取支付状态文本
    const getPaymentStatusText = (status: string | null | undefined) => {
      if (!status) return '未知'
      const statusMap: Record<string, string> = {
        PENDING: '待支付',
        PAID: '已支付',
        FAILED: '支付失败',
        REFUNDED: '已退款'
      }
      return statusMap[status] || '未知状态'
    }
    
    // 获取支付方式文本
    const getPaymentMethodText = (method: string | null | undefined) => {
      if (!method) return '未知'
      const methodMap: Record<string, string> = {
        ALIPAY: '支付宝',
        WECHAT: '微信支付',
        BALANCE: '余额支付'
      }
      return methodMap[method] || '未知方式'
    }
    
    // 获取订单项类型文本
    const getItemTypeText = (type: string | null | undefined) => {
      if (!type) return '未知'
      const typeMap: Record<string, string> = {
        COURSE: '课程',
        TEST: '测评',
        CONSULTATION: '咨询'
      }
      return typeMap[type] || '未知类型'
    }
    
    // 生命周期钩子
    onMounted(() => {
      loadOrderDetail()
    })
    
    return {
      loading,
      error,
      orderDetail,
      loadOrderDetail,
      copyOrderNo,
      goToPayment,
      cancelOrder,
      formatDate,
      formatAmount,
      getStatusTagType,
      getStatusText,
      getPaymentStatusTagType,
      getPaymentStatusText,
      getPaymentMethodText,
      getItemTypeText
    }
  }
})
</script>

<style scoped>
.order-detail-container {
  padding: 20px;
  max-width: 1200px;
  margin: 0 auto;
}

.breadcrumb {
  margin-bottom: 20px;
}

.loading-container {
  padding: 20px;
}

.error-container {
  padding: 40px 0;
}

.order-detail-content {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.status-card {
  margin-bottom: 20px;
}

.status-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.status-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.status-info h2 {
  margin: 0;
  color: #303133;
}

.order-actions {
  display: flex;
  gap: 12px;
}

.order-basic-info {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.info-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.info-item .label {
  color: #606266;
  min-width: 80px;
}

.info-item .value {
  color: #303133;
  font-weight: 500;
}

.card-header {
  font-weight: 500;
  color: #303133;
}

.order-items {
  padding: 20px 0;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 20px;
}

.item-info {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
}

.item-title {
  font-size: 16px;
  font-weight: 500;
  color: #303133;
  margin-bottom: 8px;
}

.item-meta {
  display: flex;
  gap: 12px;
}

.item-type {
  font-size: 14px;
  color: #909399;
}

.order-amount {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.amount-row {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.amount-row .label {
  color: #606266;
}

.amount-row .value {
  color: #303133;
  font-weight: 500;
}

.amount-row .value.discount {
  color: #67c23a;
}

.amount-row.total {
  padding-top: 12px;
  border-top: 1px solid #ebeef5;
  font-size: 16px;
}

.amount-row.total .label {
  font-weight: 500;
}

.amount-row.total .total-amount {
  color: #f56c6c;
  font-size: 18px;
  font-weight: 600;
}

.payment-info {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.payment-status {
  display: flex;
  align-items: center;
}

.transaction-info {
  display: flex;
  align-items: center;
  gap: 8px;
}

.transaction-info .label {
  color: #606266;
}

.transaction-info .value {
  color: #303133;
  font-family: monospace;
}
</style>